#coding = utf-8

from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse
from django.http import StreamingHttpResponse
from api.models import category as cate
from api.models import contract as cont
import time, sys

#打印欢迎信息
def welcome(request):
    return HttpResponse('Welcome to use T220 API!')

def categoryDB2Json(tableLines):
    data = []
    for line in tableLines:
        ret = {}
        ret['id'] = line._id
        ret['name'] = line.name
        ret['priority'] = line.priority
        ret['visable'] = line.state
        data.append(ret)
    if len(data) > 1:
        return data
    return ret

def contractDB2Json(tableLines, flag = 0):
    data = []
    for line in tableLines:
        ret = {}
        ret['id'] = line._id
        ret['title'] = line.title
        if flag == 0:
            ret['publishAt'] = str(line.publishAt)
        if flag == 1:
            ret['content'] = line.content
            ret['visable'] = line.state
        if flag == 2:
            ret['publishAt'] = str(line.publishAt)
            ret['content'] = line.content
            ret['download'] = line.state
        if flag == 3:
            ret['categoryId'] = line.categoryId
            ret['content'] = line.content
            ret['pulishAt'] = str(line.publishAt)
            ret['visable'] = line.state
        data.append(ret)
    if len(data) > 1:
        return data
    return ret

@csrf_exempt
def category(request):
    method = request.method
    if method == 'GET':
        #获取所有的合同分类
        c = cate.objects.order_by('_id')
        data = categoryDB2Json(c)
        return HttpResponse(jsonProcess(data), status = 200)
    elif method == 'POST':
        params = request.POST
        print('params:', params)
        if 'name' in params:
            name = params['name']
            #检查名字是否重复
            c = cate.objects.filter(name = name)
            if getLength(c) != 0:
                data = {"reason":"name_duplicated"}
                return HttpResponse(jsonProcess(data), status = 409)
            parents = 0
            visable = True
            priority = 1
            if 'parents' in params:
                parents = params['parents']
            if 'priority' in params:
                priority = params['priority']
            id = getValidId()
            #开始插入数据
            c = cate(_id = id, name = name, parents = parents, state = visable, priority = priority)
            c.save()
            time.sleep(1)
            #查询数据,返回数据
            c = cate.objects.filter(name = name)
            data = categoryDB2Json(c)
            return HttpResponse(jsonProcess(data), status = 201)
        else:
            data = 'Name is needed!'
            return HttpResponse(data, status = 409)    
    else:
        data = 'Welcome to use t220 API!'
        return HttpResponse(data)
    
@csrf_exempt
def categoryHandle(request, categoryId):
    c = cate.objects.filter(_id = categoryId)
    #查询id是否存在, 若不存在, 则直接打印错误信息!
    if not c:
        return HttpResponse('Error:CategoryId is not exists!')

    #PUT方法用于修改内容
    if request.method == 'PUT':
        params = request.read().decode('utf-8')
        try:
            params = eval(params)
        except:
            return HttpResponse('Error:Param is invalid!', status = 200)
            sys.exit()
        
        #更新name
        if 'name' in params:
            c_name = cate.objects.filter(name = params['name'])
            if getLength(c_name):
                data = {"reason":"name_duplicated"}
                return HttpResponse(jsonProcess(data), status = 409)
            else:
                for items in c:
                    items.name = params['name']
                    items.save()

        #更新priority
        if 'priority' in params:
            for items in c:
                items.priority = params['priority']
                items.save()

        #更新visable
        if 'visable' in params:
            for items in c:
                items.state = params['visable']
                items.save()

        #返回信息
        c = cate.objects.filter(_id = categoryId)
        data = categoryDB2Json(c)
        return HttpResponse(jsonProcess(data), status = 200)

    #delete为删除内容
    elif request.method == 'DELETE':
        print('categoryId:', categoryId)
        #查询categoryId下是否包含合同
        c = cont.objects.filter(categoryId = categoryId)
        num = 0
        for items in c:
            num += 1
        #查询category是否是其它category的父ID
        c = cate.objects.filter(parents = categoryId)
        for items in c:
            num += 1
        if num != 0:
            data = {"reason":"dependency_found"}
            return HttpResponse(jsonProcess(data), status = 403)
        #删除合同并返回信息
        c = cate.objects.filter(_id = categoryId)
        c.delete()
        c = cate.objects.filter(_id = categoryId)
        num = 0
        for items in c:
            num += 1
        if num != 0:
            return HttpResponse('Error:Delete category failed!', status = 200)
        else:
            data = {"action":"success"}
            return HttpResponse(jsonProcess(data), status = 200)
    else:
        return requestMethodNotDefined(request)

@csrf_exempt        
def categoryContractHandle(request, categoryId):
    #获取categoryId下所有的合同
    c = cont.objects.filter(categoryId = categoryId)
    if request.method == 'GET':
        data = contractDB2Json(c)
        return HttpResponse(jsonProcess(data), status = 200)
    else:
        return requestMethodNotDefined(request)

@csrf_exempt
def contract(request):
    #POST用于添加合同内容
    if request.method == 'POST':
        params = request.POST
        if 'title' in params and 'content' in params and 'categoryId' in params:
            title = params['title']
            content = params['content']
            categoryId = int(params['categoryId'])
            c = cont.objects.filter(title = title)
            num = 0
            for items in c:
                num += 1
            if num != 0:    
                data = {"reason":"name_duplicated"}
                return HttpResponse(jsonProcess(data), status = 409)
            if 'priority' in params:
                priority = int(params['priority'])
            else:
                priority = 100
            id = getValidId(1) 
            c = cont(_id = id, categoryId = categoryId, title = title, content = content, \
                    publishAt = time.strftime('%Y-%m-%d'), state = True)
            c.save()
            c = cont.objects.filter(title = title)
            data = contractDB2Json(c, 1)
            return HttpResponse(jsonProcess(data), status = 200)
        else:
            data = 'Error:Params is not complete!'
            return HttpResponse(jsonProcess(data), status = 200)
    else:
        return requestMethodNotDefined(request)

@csrf_exempt    
def contractHandle(request, contractId):
    c = cont.objects.filter(_id = contractId)
    #若ID不存在则报错
    if getLength(c) == 0:    
        data = 'Error:Contract is not exist!'
        return HttpResponse(data)

    #GET方法用来获取合同内容
    if request.method == 'GET':
        data = contractDB2Json(c, 2)
        return HttpResponse(jsonProcess(data), status = 200)

    #PUT方法用来增加合同
    elif request.method == 'PUT':
        #获取PUT内容
        params = request.FILES.read().decode('utf-8')
        try:
            params = eval(params)
        except:
            return HttpResponse('Error:Param is invalid!', status = 200)
            sys.exit()
        #修改合同名称
        if 'name' in params:
            c1 = cont.objects.filter(name = params['name'])
            if c1:
                data = {"reason":"name_duplicated"}
                return HttpResponse(jsonProcess(data), status = 200)
            c.name = params['name']
            c.save()
        #修改合同优先级
        if 'priority' in params:
            c.priority = params['priority']
            c.save()
        #修改状态
        if 'visable' in params:
            c.state = params['visable']
            c.save()
        #修改合同内容
        if 'content' in params:
            c.content = params['content']
            c.save()
        c = cont.objects.filter(contract = contractId)
        data = contractDB2Json(c, 1)
        return HttpResponse(jsonProcess(data), status = 200)
        '''
        if not c.state:
            data = {"reason":"no_permissions"}
            return HttpResponse(jsonProcess(data), status = 403)
        '''
    #DELETE方法用来删除合同
    elif request.method == 'DELETE':
        c.delete()
        c = cont.objects.filter(_id = contractId)
        if not c:
            data = {"action":"success"}
            return HttpResponse(jsonProcess(data), status = 200)
        else:
            return HttpResponse('Error:Delete contract error!', status = 200)
        '''
        if not c.state:
            data = {"reason":"no_permissions"}
            return HttpResponse(jsonProcess(data), status = 403)
        '''
    else:
        return requestMethodNotDefined(request)

#用于下载合同内容
@csrf_exempt
def download(request, contractId):

    def file_iterator(filename, buffer = 128):
        with open(filename) as f:
            while True:
                c = f.read(buffer)
                if c:
                    yield c
                else:
                    break

    c = cont.objects.filter(_id = contractId)
    if getLength(c):
        data = contractDB2Json(c, 3)
        print(data)
        fileObj = open('tmp', 'w')
        fileObj.write(str(data))
        fileObj.close()
        response = StreamingHttpResponse(file_iterator('tmp'))
        response['Content-Type'] = 'application/octent-stream'
        response['Content-Disposition'] = 'attachment;filename="contract' + str(contractId) + '"' 
        return response
    else:
        data = 'Error:Contract ' + str(contractId) + ' is not exist!'
        return HttpResponse(data, status = 200)

#当URL非法时打印URL不存在的提示
def urlNotExists(request):
    data = 'Error:The reqeust URL is not exsits!'
    return HttpResponse(data)

#请求方法未定义错误提示!
def requestMethodNotDefined(request):
    data = 'Error:The reqeust method is not defined!'
    return HttpResponse(data)

#用于在web上格式化打印json数据!
def jsonProcess(data):
    import json
    return json.dumps(data, indent = 2, ensure_ascii = False)
    '''
    return json.dumps(data, indent = 2, ensure_ascii = False).replace("\n", \
        '<br>').replace(' ', '&nbsp;')
    '''

#获取可用的ID
def getValidId(flag = 0):
    id = 1
    while True:
        if flag == 0:
            c = cate.objects.filter(_id = id)
        elif flag == 1:
            c = cont.objects.filter(_id = id)
        else:
            return None

        if not c:
            return id
        else:
            id += 1
    return id

#获取查询结果的条目数
def getLength(c):
    num = 0
    for items in c:
        num += 1
    return num
